package cn.woniu.wxy.handler;

import cn.woniu.wxy.util.ResponseResult;
import com.alibaba.fastjson.JSON;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 前后端分离的情况下：用户未登录直接访问系统资源，
 * 会被拦截
 */
public class MyAuthenticationEntrypoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        httpServletRequest.setCharacterEncoding("utf-8");
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setContentType("application/json;charset=utf8");
        PrintWriter writer = httpServletResponse.getWriter();

        String json = JSON.toJSONString(ResponseResult.NOLOGIN);
        writer.print(json);
        writer.flush();
        writer.close();
    }
}
